﻿#include "alltodolists.h"
#include "ui_alltodolists.h"
#include <todolistitemfragment.h>
#include <QInputDialog>
#include <QDir>
#include "loader.h"
#include <QDebug>
AllTODOLists::AllTODOLists(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AllTODOLists)
{
    ui->setupUi(this);
    this->layout = new QGridLayout;

    QDir dir("./savings/todolists/");
    QStringList fliter;
    fliter<<"*.json";
    QStringList files = dir.entryList(fliter,QDir::Files|QDir::Readable, QDir::Name);
    for(auto name:files){
        QVector<TODOList> lists = Loader::loadTODOList("./savings/todolists/"+name);
        qDebug()<<"./savings/todolists/"+name+".json";
        addList(lists[0]);
    }
    ui->scrollArea->widget()->setLayout(layout);
}

AllTODOLists::~AllTODOLists()
{
    delete ui;
}

void AllTODOLists::addList(TODOList list)
{
    this->lists[list.getName()] = list;
    TODOListItemFragment *fragment = new TODOListItemFragment(list);
    fragment->setMinimumSize(QSize(fragment->geometry().width(),fragment->geometry().height()));
    this->layout->addWidget(fragment);
}

void AllTODOLists::on_pushButton_clicked()
{
    bool ok;
    QString name = QInputDialog::getText(this,tr("please input name"),tr("please input name"),QLineEdit::Normal,"",&ok);
    if(!ok||name.isEmpty()){
        return;
    }
    TODOList list(name);
    addList(name);
}

void AllTODOLists::on_pushButton_2_clicked()
{
    for(int i = 0;i<layout->count();i++){
        QLayoutItem* pLayout = layout->itemAt(i);
        TODOListItemFragment *frag = (TODOListItemFragment*)pLayout->widget();
        if(frag->isChosen()){
            frag->deleteLater();
            QFile file("./savings/todolists/todolist"+frag->getList().getName()+".json");
            if(file.exists())file.remove();
        }
    }

}
